Popular Searches
Popular Course Categories
Popular Courses

Default Values for Props

Default Values for Props

Props in React

Default Values for Props in React

Course: React JS Training

Topic: Default Values for Props

Learning Objectives: Understand default props, learn how to set fallback values in functional components, use destructuring, handle missing or undefined props, apply defaults to different data types, and build reusable React components with sensible default values.


1. Introduction to Default Values for Props

In React, props are used to pass data from a parent component to a child component. Sometimes, a parent component may not provide a value for every prop. In such cases, a component can use a default value as a fallback.

Default values help ensure that a component can display meaningful content even when an optional prop is not provided.

Example

function Greeting({ name = "Guest" }) {
  return <h1>Welcome, {name}!</h1>;
}
function App() {
  return (
    <div>
      <Greeting name="Amit" />
      <Greeting />
    </div>
  );
}
export default App;

Output:

Welcome, Amit!
Welcome, Guest!

Explanation: The first component receives the name "Amit". The second component does not receive a name, so it uses the default value "Guest".


2. Why Are Default Props Important?

Default values make React components more flexible, predictable, and reusable.

  • Prevent missing content: Display a fallback when an optional value is not provided.
  • Improve reusability: Use the same component with or without optional props.
  • Reduce repetitive code: Avoid writing the same fallback logic in multiple places.
  • Improve readability: Make the intended fallback behaviour clear.
  • Support flexible interfaces: Provide default titles, labels, sizes, themes, and descriptions.
  • Simplify component usage: Callers do not need to provide every optional value.

3. Setting Default Values with Destructuring

The recommended approach for default values in modern functional components is to use JavaScript default values in the function parameter's destructuring pattern.

Syntax

function Component({ propName = defaultValue }) {
  return <p>{propName}</p>;
}

Example

function UserProfile({ name = "Unknown User" }) {
  return <h2>User Name: {name}</h2>;
}
function App() {
  return (
    <div>
      <UserProfile name="Neha" />
      <UserProfile />
    </div>
  );
}
export default App;

Output:

User Name: Neha
User Name: Unknown User

Explanation: When the name prop is omitted, the component uses "Unknown User".


4. Default Values for Multiple Props

A component can define default values for several props in the same destructuring parameter. Each default is applied independently when its corresponding prop is missing or set to undefined.

Example

function ProductCard({
  name = "Unnamed Product",
  price = 0,
  category = "General",
  inStock = false
}) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Price: ₹{price}</p>
      <p>Category: {category}</p>
      <p>{inStock ? "In Stock" : "Out of Stock"}</p>
    </div>
  );
}
function App() {
  return (
    <div>
      <ProductCard name="Keyboard" price={1200} inStock={true} />
      <ProductCard />
    </div>
  );
}
export default App;

Explanation:

  • name defaults to "Unnamed Product".
  • price defaults to 0.
  • category defaults to "General".
  • inStock defaults to false.

This approach is useful when building reusable product cards, profile components, buttons, and other UI elements.


5. When Are Default Values Applied?

JavaScript destructuring defaults are used when a property is missing or its value is undefined. They are not used for every falsy value.

Value Passed Example Is the Default Used?
Prop omitted Yes
Undefined Yes
Null No
Empty string No
Zero No
False No

Example: Undefined vs. Null

function Greeting({ name = "Guest" }) {
  return <p>Hello, {String(name)}!</p>;
}
function App() {
  return (
    <div>
      <Greeting name={undefined} />
      <Greeting name={null} />
      <Greeting name="" />
    </div>
  );
}

Output:

Hello, Guest!
Hello, null!
Hello, !

Important: The default value is not a general replacement for empty or invalid data. If you want to handle null or empty strings too, add explicit fallback logic.


6. Using Logical OR for Fallback Values

The logical OR operator (||) can provide a fallback when a value is falsy. This includes empty strings, zero, false, null, and undefined.

Example

function Greeting({ name }) {
  const displayName = name || "Guest";
  return <h2>Welcome, {displayName}!</h2>;
}

Explanation: If name is an empty string or another falsy value, the component uses "Guest".

Warning: Logical OR may replace valid values such as 0 and false. Use it only when those values should also trigger the fallback.


7. Using the Nullish Coalescing Operator

The nullish coalescing operator (??) provides a fallback only when the value is null or undefined. Unlike ||, it preserves valid values such as 0, false, and an empty string.

Example

function Counter({ count }) {
  const displayCount = count ?? 10;
  return <p>Count: {displayCount}</p>;
}

Examples:

count Value Result with count ?? 10
undefined 10
null 10
0 0
false false
5 5

Use ?? when only nullish values should trigger the fallback. Use a destructuring default when the default should apply to a missing prop or undefined.


8. Default Values for String Props

String defaults are useful for names, headings, labels, button text, and descriptions.

Example

function Button({ label = "Click Here" }) {
  return <button>{label}</button>;
}
function App() {
  return (
    <div>
      <Button label="Submit Form" />
      <Button />
    </div>
  );
}
export default App;

Output: One button displays "Submit Form" and the other displays "Click Here".


9. Default Values for Number Props

Numeric defaults can be used for counts, dimensions, ratings, prices, and image sizes.

Example

function Avatar({ size = 100 }) {
  return (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: "50%",
        backgroundColor: "lightgray"
      }}
    >
      Avatar
    </div>
  );
}
function App() {
  return (
    <div>
      <Avatar size={150} />
      <Avatar />
    </div>
  );
}
export default App;

Explanation: The first avatar uses a size of 150 pixels. The second uses the default size of 100 pixels.


10. Default Values for Boolean Props

Boolean defaults are useful when a component has an optional feature that should be enabled or disabled by default.

Example

function Notification({ showIcon = true }) {
  return (
    <p>
      {showIcon ? "🔔 " : ""}
      New notification received.
    </p>
  );
}
function App() {
  return (
    <div>
      <Notification />
      <Notification showIcon={false} />
    </div>
  );
}
export default App;

Explanation: The icon appears by default. Passing showIcon={false} disables it.


11. Default Values for Array Props

Array defaults allow a component to work when no list is supplied. You can use an empty array when there are no items to display.

Example

function CourseList({ courses = [] }) {
  if (courses.length === 0) {
    return <p>No courses available.</p>;
  }
  return (
    <ul>
      {courses.map((course) => (
        <li key={course.id}>{course.name}</li>
      ))}
    </ul>
  );
}
function App() {
  return (
    <div>
      <CourseList courses={[{ id: 1, name: "React JS" }]} />
      <CourseList />
    </div>
  );
}
export default App;

Explanation: When the courses prop is omitted, it defaults to an empty array. The component then displays a message instead of trying to render missing data.


12. Default Values for Object Props

Object defaults are useful when a component expects structured information, such as user details or configuration settings.

Example

const defaultUser = {
  name: "Guest User",
  city: "Not specified"
};
function UserProfile({ user = defaultUser }) {
  return (
    <div>
      <h2>{user.name}</h2>
      <p>City: {user.city}</p>
    </div>
  );
}
function App() {
  return (
    <div>
      <UserProfile user={{ name: "Amit", city: "Mumbai" }} />
      <UserProfile />
    </div>
  );
}
export default App;

Explanation: The component uses the supplied object when one is provided. If the user prop is omitted or undefined, it uses defaultUser.

Note: This default does not apply when user={null}. Also, avoid mutating shared default objects or arrays.


13. Default Values for Function Props

Sometimes a component accepts a callback function as an optional prop. You can provide a default no-operation function when the component should remain usable without a callback.

Example

function ActionButton({ onAction = () => {} }) {
  return (
    <button onClick={onAction}>
      Perform Action
    </button>
  );
}
function App() {
  return (
    <div>
      <ActionButton onAction={() => alert("Action completed!")} />
      <ActionButton />
    </div>
  );
}
export default App;

Explanation: The first button runs the supplied callback. The second uses the default empty function, so clicking it does not perform an additional action.

Best practice: Use a no-operation default only when doing nothing is an appropriate fallback. If a callback is essential, require it and handle the requirement explicitly.


14. The Older defaultProps Approach

Older React examples often use a static defaultProps property. In modern React, function components should use JavaScript default parameter values instead. React 19 no longer applies defaultProps to function components.

Modern Functional Component

function Greeting({ name = "Guest" }) {
  return <h1>Hello, {name}!

Class Component Example

import { Component } from "react";
class Greeting extends Component {
  static defaultProps = {
    name: "Guest"
  };
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}
export default Greeting;

Explanation: Class components still support static defaultProps. For new functional components, use destructuring defaults.


15. Default Values in TypeScript React Components

In TypeScript, an optional prop can be marked with ? and assigned a default value through destructuring. This allows callers to omit the prop while ensuring the component has a usable value.

Example

type GreetingProps = {
  name?: string;
};
function Greeting({ name = "Guest" }: GreetingProps) {
  return <h1>Hello, {name}!</h1>;
}
export default Greeting;

Explanation: The question mark in name?: string indicates that the prop is optional. If the caller omits it, the component uses "Guest".


16. Common Mistakes When Setting Default Values

Mistake Correct Approach
Assuming defaults replace null values Handle null explicitly if it should trigger a fallback.
Using || when zero is valid Use ?? or a destructuring default when appropriate.
Using function-component defaultProps in React 19 Use parameter destructuring defaults.
Mutating default objects or arrays Treat them as immutable and create new values for updates.
Providing confusing fallback content Choose clear, meaningful defaults.
Making an essential callback silently do nothing Require the callback or handle the missing callback deliberately.
Using a default that hides a data error Validate required data and display an appropriate error when necessary.

17. Best Practices for Default Values

  • Use destructuring defaults for functional components.
  • Choose sensible defaults that fit the component's purpose.
  • Use optional props for values that can safely be omitted.
  • Remember that defaults apply to missing and undefined values, not null values.
  • Use ?? when only null or undefined should trigger a fallback.
  • Use || only when all falsy values should trigger a fallback.
  • Avoid mutating objects or arrays used as defaults.
  • Keep defaults close to the component that uses them.
  • Use TypeScript or other validation techniques when appropriate for required data.
  • Follow modern React conventions and avoid outdated function-component defaultProps patterns.

18. Practical Project: Reusable Profile Card

Objective: Create a reusable profile card that uses default values when optional information is missing.

App.jsx

function ProfileCard({
  name = "Guest User",
  role = "Learner",
  city = "Not specified",
  isActive = true
}) {
  return (
    <div className="profile-card">
      <h2>{name}</h2>
      <p>Role: {role}</p>
      <p>City: {city}</p>
      <p>Status: {isActive ? "Active" : "Inactive"}</p>
    </div>
  );
}
export default function App() {
  return (
    <div>
      <ProfileCard
        name="Amit Sharma"
        role="React Developer"
        city="Mumbai"
      />
      <ProfileCard name="Neha" isActive={false} />
      <ProfileCard />
    </div>
  );
}

Project Explanation

  • The first profile uses supplied values and the default active status.
  • The second profile uses default role and city values and explicitly sets the status to inactive.
  • The third profile uses all default values.
  • The same component can display many profiles without repeating its structure.

Suggested Improvements

  • Add a default avatar image URL.
  • Add a default description for users without a biography.
  • Add a prop to control whether contact information is displayed.
  • Style the profile card using CSS.

19. Interview Questions and Answers

Q1. What are default values for props in React?

Answer: Default values are fallback values used when a prop is not provided or is set to undefined.

Q2. How do you set a default value in a functional component?

Answer: Use destructuring defaults, such as function Greeting({ name = "Guest" }).

Q3. Do default values apply when a prop is null?

Answer: No. Destructuring defaults apply when the prop is missing or undefined, not when it is null.

Q4. What is the difference between || and ???

Answer: || uses the fallback for any falsy value, while ?? uses the fallback only for null or undefined.

Q5. Can multiple props have default values?

Answer: Yes. You can define defaults for several props in the same destructuring parameter.

Q6. Is defaultProps supported for function components in React 19?

Answer: React 19 no longer applies defaultProps to function components. Use JavaScript default parameter values instead.

Q7. Are defaultProps still supported for class components?

Answer: Yes. Class components continue to support static defaultProps.

Q8. Can an object or array be used as a default value?

Answer: Yes. They can be used as defaults, but should be treated as immutable and not modified directly.

Q9. Why are default values useful?

Answer: They improve reusability, reduce repetitive fallback logic, and help components render meaningful content when optional props are omitted.

Q10. How do you mark a prop as optional in TypeScript?

Answer: Add a question mark to the property in the props type, such as name?: string.


20. Practice Exercises

  1. Create a Greeting component with a default name of "Guest".
  2. Create a Button component with a default label of "Click Here".
  3. Create a ProductCard with default name, price, category, and stock status.
  4. Create an Avatar component with a default size of 100.
  5. Create a CourseList that defaults to an empty array.
  6. Create a ProfileCard with default name, role, and city.
  7. Demonstrate the difference between destructuring defaults, ||, and ??.
  8. Create a TypeScript component with an optional prop and a default value.

21. Quick Revision Checklist

  • Default values provide fallbacks for missing or undefined props.
  • Functional components should generally use destructuring defaults.
  • Defaults do not automatically replace null, zero, false, or empty strings.
  • The || operator replaces all falsy values.
  • The ?? operator replaces only null and undefined.
  • React 19 no longer applies defaultProps to function components.
  • Class components still support static defaultProps.
  • Objects, arrays, numbers, strings, and Booleans can all have defaults.
  • Default values should be sensible, clear, and safe to use.

22. Official Documentation and Course Links

Explore the official React documentation for more information about props and default values:

JustAcademy React JS Training


23. Conclusion

Default values for props make React components more reliable and reusable. By providing sensible fallback values, developers can handle optional information without duplicating code. For functional components, destructuring defaults are the recommended modern approach. Understanding the differences between missing values, undefined, null, and other falsy values will help you write clearer and more predictable React applications.

whatsapp